package cn.tedu.luban.demand.main.service;

import cn.tedu.luban.demand.main.repository.DemandRepository;
import cn.tedu.luban.demand.protocol.bo.RequestOrderBO;
import cn.tedu.luban.demand.protocol.query.RequestOrderQuery;
import com.tedu.inn.protocol.ListRecordTotalBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
public class DemandService {

    @Autowired
    private DemandRepository demandRepository;

    public ListRecordTotalBO<RequestOrderBO> searchRequestOrders(RequestOrderQuery query) {
        // 1. 使用仓储层查询总数
        Long total = demandRepository.getRequestOrderCount(query);

        ListRecordTotalBO<RequestOrderBO> bos = null;
        if(total == 0){ // 2. 如果没有数据，则返回空对象
            bos = new ListRecordTotalBO<>(null,total);
        }else{ // 3. 如果有数据，则分页查询数据
            List<RequestOrderBO> list = demandRepository.queryRequestOrders(query);
            //计算展示价格
            calculateViewAmount(list);
            bos = new ListRecordTotalBO<>(list,total);
        }
        return bos;
    }

    /**
     * 计算展示价格:
     * order_amount 原始价格(表字段)
     * profit_Scale 利润比例(固定 20)
     * view_amount 展示价格(师傅看到的价格)
     *
     * 展示价格 = 原始价格 * (100-利润比例)/100
     */
    private void calculateViewAmount(List<RequestOrderBO> list) {
        // 定死每一个需求单的分润比例为 20
        BigDecimal profitScale = new BigDecimal("20");

        if (!CollectionUtils.isEmpty(list)) {
            // 遍历需求单列表
            for (RequestOrderBO bo : list) {
                // 获取当前需求单的原始价格
                Long orderAmount = bo.getOrderAmount();
                // 计算每个订单的分润 (100-利润比例)/100=80%
                BigDecimal workerPercent = new BigDecimal("100").subtract(profitScale).divide(new BigDecimal("100"));
                // 计算每个订单的展示价格
                long viewOrderAmount = new BigDecimal(orderAmount).multiply(workerPercent).longValue();
                // 设置展示价格
                bo.setViewOrderAmount(viewOrderAmount);
                bo.setProfitScale(profitScale);
            }
        }
    }

    public Boolean grabOrder(String requestOrderNo) {
        // update request_order set grab_status=1 where reqeust_order_no="abc" and grab_status=0
        // 直接调用仓储层
        Integer count = demandRepository.grabOrder(requestOrderNo);
        return count==1;
    }

    public Boolean returnOrder(String requestOrderNo) {
        // update request_order set grab_status=0 where reqeust_order_no="abc" and grab_status=1
        // 直接调用仓储层
        Integer count = demandRepository.returnOrder(requestOrderNo);
        return count==1;
    }
}
